package auth

import (
	"github.com/dgrijalva/jwt-go"
	"gysa-share01/exception"
	"gysa-share01/models/db"
	user2 "gysa-share01/models/user"
	"time"
)

var (
	UserDoesNotExistError         = exception.NewGeneralException("用户不存在!", exception.RESOURCE_DOES_NOT_EXIST)
	UsernameOrPasswordIsIncorrect = exception.NewGeneralException("用户名或者密码错误!", exception.PARAMETER_ERROR)
)

type AuthServiceInterface interface {
	LoginByPwd(username, password string) (string, error)
	RegisterByPwd(*user2.User) (string, error)
}

type AuthService struct {
}

func (a AuthService) LoginByPwd(username, password string) (string, error) {

	database, err := db.Instance()
	if err != nil {
		return "", err
	}
	var user user2.User
	//查询用户
	database.Where("username = ?", username).First(&user)
	if (user == user2.User{}) {
		return "", UserDoesNotExistError
	}

	pwdMatch := ComparePasswords(user.Password, []byte(password))
	if !pwdMatch {
		return "", UsernameOrPasswordIsIncorrect
	}

	authClaims := AuthClaims{Uid: user.ID, Nickname: user.Nickname}
	authClaims.ExpiresAt = time.Now().Add(time.Hour).Unix()
	token := jwt.NewWithClaims(JWTMethod, authClaims)

	tokenString, err := token.SignedString(JWTKey)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

func (a AuthService) RegisterByPwd(user *user2.User) (tokenString string, err error) {
	database, err := db.Instance()
	if err != nil {
		return
	}
	//加密密码
	user.Password = HashAndSalt([]byte(user.Password))
	err = database.Create(user).Error
	if err != nil {
		return
	}

	authClaims := AuthClaims{Uid: user.ID, Nickname: user.Nickname}
	token := jwt.NewWithClaims(JWTMethod, authClaims)
	tokenString, err = token.SignedString(JWTKey)
	return

}
